package servlets;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.ejb.EJB;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import security.Encryption;
import security.EncryptionType;

import entities.User;

import managers.UserManager;

/**
 * Servlet implementation class RecoveryServlet
 */
@WebServlet("/Recovery")
public class RecoveryServlet extends HttpServlet {
	@EJB
	UserManager userManager;	
	private static final long serialVersionUID = 1L;
	
    public RecoveryServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String email = "";
		User user = null;
		if(username != null){
			user = userManager.getUser(username, false);
		}else if((email = request.getParameter("email")) != null){
			user = userManager.getUser(email, true);
		}else{
			System.out.println("Both parameters null");
			//can't find user based on username or email
		}
		if(user != null){		
			final String smtpusername = "andrew.c.wedekind@gmail.com";
			final String smtppassword = "nubwub64";
			
			
			
			Properties props = new Properties();
			props.put("mail.smtp.auth", true);
			props.put("mail.smtp.host",  "smtp.gmail.com");
			props.put("mail.smtp.port", "587");
			props.put("mail.smtp.starttls.enable", true);
			props.put("mail.debug", true);
			
			Session session = Session.getInstance(props, new javax.mail.Authenticator(){
				protected PasswordAuthentication getPasswordAuthentication(){
					return new PasswordAuthentication(smtpusername, smtppassword);
				}
			});
			
			try {
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress(smtpusername));
				InternetAddress[] recipients = {new InternetAddress(user.getEmail())};
				msg.setRecipients(Message.RecipientType.TO, recipients);
				
				msg.setSubject("Account Recovery - Capstone");
				msg.setSentDate(new Date());
				
				Random rand = new Random();
				char[] tempPass = new char[15];
				for(int i = 0; i < 15; i ++){
					tempPass[i] = (char) rand.nextInt();
				}
				String newTempPassword = tempPass.toString();
				user.setPassword(Encryption.digest(newTempPassword));
				userManager.update(user);
				
				String recoveryMessage = "Hello " + user.getFname() + " " + user.getLname() +
						"\n If you did not request your account recovery info disreguard this email." +
						"\n \n Username: " + user.getUsername() + "\n Password: " + newTempPassword;
				
				msg.setText(recoveryMessage);
				
				
				Transport.send(msg);
			} catch (AddressException e) {e.printStackTrace();
			} catch (MessagingException e) {e.printStackTrace();
			}			
		}else{
			System.out.println("Unable to find user");
			//can't find user
		}	
		
		response.sendRedirect("index.jsp");
	}
}
